<?php

namespace Modules\Wechat\Model\Util\Dao;

use Dao\Db;

class Creator
{
    public static function echoDaoFile(array $table_names)
    {
        if (!$table_names = array_filter($table_names)) {
            return false;
        }
        $table_info = static::getTableInfo($table_names);
        foreach (static::getColumnInfo($table_names) as $table_name => $column_info) {
            static::echoInfo($column_info, $table_info[$table_name]);
        }
        return true;
    }

    protected static function getVarType($mysql_data_type)
    {
        $mysql_data_type = strtolower($mysql_data_type);
        switch ($mysql_data_type) {
            case (false !== strpos($mysql_data_type, 'int')):
                return 'int';
            case ('decimal' == $mysql_data_type):
                return 'float';
            case ('datetime' == $mysql_data_type):
            case ('timestamp' == $mysql_data_type):
            default:
                return 'string';
        }
    }

    protected static function getVarDefault($mysql_data_type)
    {
        $mysql_data_type = strtolower($mysql_data_type);
        switch ($mysql_data_type) {
            case (false !== strpos($mysql_data_type, 'int')):
                return '0';
            case ('decimal' == $mysql_data_type):
                return '0.00';
            case ('datetime' == $mysql_data_type):
                return '0000-00-00 00:00:00';
            case ('timestamp' == $mysql_data_type):
            default:
                return '';
        }
    }

    protected static function getColumnInfo(array $table_names, $db_name = Db::DB_NAME)
    {
        $info = [];
        if (empty($table_names)) {
            return $info;
        }
        foreach ($table_names as $table_name) {
            $sql = " SELECT TABLE_SCHEMA AS db_name, TABLE_NAME AS table_name, COLUMN_NAME AS col_name, DATA_TYPE AS data_type, COLUMN_KEY AS col_key, COLUMN_COMMENT AS col_comment";
            $sql .= " FROM INFORMATION_SCHEMA.COLUMNS";
            $sql .= " WHERE TABLE_SCHEMA = '{$db_name}' AND TABLE_NAME = '{$table_name}'";
            $info[$table_name] = Db::db()->qsql($sql);
        }
        return $info;
    }

    protected static function getTableInfo(array $table_names, $db_name = Db::DB_NAME)
    {
        $info = [];
        if (empty($table_names)) {
            return $info;
        }
        foreach ($table_names as $table_name) {
            $sql = 'SELECT TABLE_SCHEMA as db_name, TABLE_NAME AS table_name, TABLE_COMMENT AS table_comment';
            $sql .= ' FROM INFORMATION_SCHEMA.TABLES';
            $sql .= " WHERE TABLE_SCHEMA='{$db_name}' AND TABLE_NAME='{$table_name}'";
            $info[$table_name] = Db::db()->qsqlone($sql);
        }
        return $info;
    }

    const TABLE_COMMENT_DELIMITER = '：';

    protected static function getDaoName($table_comment, $delimiter = self::TABLE_COMMENT_DELIMITER)
    {
        if (!$table_comment || false === strpos($table_comment, $delimiter)) {
            return $table_comment;
        }
        return mb_substr($table_comment, 0, strpos($table_comment, $delimiter));
    }

    protected static function getDaoClassName($table_name)
    {
        return ucfirst(substr($table_name, strrpos($table_name, '_') + 1));
    }

    protected static function getTableNameWithoutPrefix($table_name)
    {
        return substr($table_name, strpos($table_name, '_') + 1);
    }

    protected static function extractInfo(array $column_info, array $table_info)
    {


        $info = [
            'name'          => static::getDaoName($table_info['table_comment']),
            'class_name'    => static::getDaoClassName($table_info['table_name']),
            'table_name'    => static::getTableNameWithoutPrefix($table_info['table_name']),
            'table_comment' => $table_info['table_comment'],
            'col'           => [],
        ];
        foreach ($column_info as $col_info) {

            $col['name']    = $col_info['col_name'];
            $col['type']    = static::getVarType($col_info['data_type']);
            $col['default'] = static::getVarDefault($col_info['data_type']);
            $col['comment'] = $col_info['col_comment'];
            $col['key']     = 'pri' == strtolower($col_info['col_key']) ? 'null' : "'{$col['default']}'";
            $info['col'][]  = $col;
        }
        return $info;
    }


    protected static function echoInfo(array $column_info, array $table_info)
    {
        $info = static::extractInfo($column_info, $table_info);
        echo "/**\n";
        echo " * @name {$info['name']}\n *\n";
        echo " * {$info['table_comment']}\n";
        echo " */\n";
        echo "class {$info['class_name']} extends \\Modules\\Wechat\\Model\\Dao\\Db\\Abstraction\n{\n";
        foreach ($info['col'] as $col) {
            echo "    /** @var {$col['type']} {$col['comment']} */\n";
            echo "    public \${$col['name']} = {$col['default']};\n\n";
        }
        echo "    protected function init()\n    {\n";
        echo "        return \$this->setTableName('{$info['table_name']}');\n";
        echo "    }\n}\n";
    }

    protected static function isPk(array $table_info, $col_key_name = 'col_key')
    {
        return isset($table_info[$col_key_name]) && 'pri' == strtolower($table_info[$col_key_name]);
    }
}